<?php
/**
 * 测试命令
 * @author yupoxiong<i@yupoxiong.com>
 */

declare (strict_types=1);


namespace app\command;

use app\admin\model\AdminUser;
use app\common\exception\CommonServiceException;
use app\common\service\StringService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class AdminResetPassword extends Command
{
    protected static $defaultName = 'admin:resetPassword';
    protected static $defaultDescription = '重置管理员用户密码';

    protected function configure()
    {
        $this->addArgument('admin_user_id', InputArgument::REQUIRED, '需要重置密码的后台用户ID');

        parent::configure();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $admin_user_id = (int)$input->getArgument('admin_user_id');

        $validate = $this->validateAdminUserId($admin_user_id);
        if ($validate !== true) {
            $output->writeln('<error>' . $validate . '</error>');
            return self::INVALID;
        }

       $result = $this->resetAdminPassword($admin_user_id);
        if($result['code']===1){
            $output->writeln('<info>修改成功，新密码：'.$result['msg'].'</info>');
        }else{
            $output->writeln('<error>修改失败，信息：'.$result['msg'].'</error>');
        }

        return self::SUCCESS;
    }

    public function validateAdminUserId($admin_user_id)
    {
        if ($admin_user_id < 1) {
            return '用户ID错误';
        }
        $admin_user = AdminUser::where('id', '=', $admin_user_id)->findOrEmpty();
        if ($admin_user->isEmpty()) {
            return '用户不存在';
        }
        return true;
    }

    public function resetAdminPassword($admin_user_id): array
    {
        try {

            $new_pass   = StringService::getRandString(6, true, true, true, false);

            $admin_user = AdminUser::where('id', '=', $admin_user_id)->findOrEmpty();

            $admin_user->password = $new_pass;
            $admin_user->save();

            return  [
                'code'=>1,
                'msg'=>$new_pass,
            ];

        } catch (CommonServiceException $e) {
            return  [
                'code'=>0,
                'msg'=>$e->getMessage(),
            ];
        }

    }
}